package d4_thread_safe;


import lombok.Synchronized;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 2024/6/23 账户类
 */

public class Account {
    private String cardId; //卡号
    private double money;//余额

    //创建一个锁对象
    private final Lock lk=new ReentrantLock();
    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }
    public Account(){

    }

    //锁住当前的实例，去访问静态方法
    public static void test(){
        synchronized (Account.class){

        }
    }
    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    //小明 小红同时过来
    //同步方法
    public synchronized void drawaMoney(double money) {
        String name = Thread.currentThread().getName();
        try {
            lk.lock();//加锁
            //1.判断余额是否足够
            synchronized (this) {
                if (this.money >= money) {
                    System.out.println(name + "来取钱" + money + "成功！");
                    this.money -= money;
                    System.out.println(name + "来取钱后,余额剩余：" + this.money);
                } else {
                    System.out.println(name + "来取钱：余额不足");
                }
            }
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            lk.unlock();
        }
    }
}
